package org.proteored.miapeapi.xml.pride;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import org.apache.log4j.Logger;
import org.proteored.miapeapi.cv.ControlVocabularyManager;
import org.proteored.miapeapi.exceptions.IllegalMiapeArgumentException;
import org.proteored.miapeapi.exceptions.MiapeDatabaseException;
import org.proteored.miapeapi.exceptions.MiapeSecurityException;
import org.proteored.miapeapi.exceptions.WrongXMLFormatException;
import org.proteored.miapeapi.interfaces.msi.MiapeMSIDocument;
import org.proteored.miapeapi.interfaces.persistence.PersistenceManager;
import org.proteored.miapeapi.interfaces.xml.MiapePrideXmlFile;
import org.proteored.miapeapi.xml.pride.autogenerated.ExperimentCollection;
import org.proteored.miapeapi.xml.pride.msi.MiapeMSIDocumentImpl;

public class MSIMiapeFactory {
	private static MSIMiapeFactory instance;
	private static Logger log = Logger.getLogger("log4j.logger.org.proteored");

	private MSIMiapeFactory() {
	}

	public static MSIMiapeFactory getFactory() {
		if (instance == null) {
			instance = new MSIMiapeFactory();
		}
		return instance;
	}

	public MiapeMSIDocument create(MiapePrideXmlFile xmlFile, PersistenceManager databaseManager,
			ControlVocabularyManager cvManager, String user, String password, String projectName)
			throws MiapeDatabaseException, MiapeSecurityException, IllegalMiapeArgumentException {
		if (cvManager == null)
			throw new IllegalMiapeArgumentException("ControlVocabularyManager is not set");
		MiapeMSIDocument result = null;
		try {
			JAXBContext jc;
			jc = JAXBContext.newInstance("org.proteored.miapeapi.xml.pride.autogenerated");

			ExperimentCollection experimentCollection = (ExperimentCollection) jc
					.createUnmarshaller().unmarshal(xmlFile.toFile());
			// TODO change to take all Experiments in the ExperimentCollection
			if (databaseManager == null) {
				result = new MiapeMSIDocumentImpl(experimentCollection.getExperiment().get(0),
						null, xmlFile.toFile().getName(), projectName, cvManager);
			} else {
				result = new MiapeMSIDocumentImpl(experimentCollection.getExperiment().get(0),
						databaseManager, cvManager, user, password, xmlFile.toFile().getName(),
						projectName);
			}
		} catch (javax.xml.bind.UnmarshalException e) {
			e.printStackTrace();
			log.info("Input file format error. Check if the input file is PRIDE schema compliant here: http://www.ebi.ac.uk/pride/validateXML.do");
			throw new WrongXMLFormatException(
					"Input file format error. Check if the input file is PRIDE schema compliant here: http://www.ebi.ac.uk/pride/validateXML.do");
		} catch (JAXBException e) {
			e.printStackTrace();
			log.info(e.getMessage());
			throw new WrongXMLFormatException(e);
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			throw new WrongXMLFormatException(e);
		}
		return result;
	}

}
